命令模式将请求封装成对象,将请求调用者和接受者解耦
类图
命令模式要素:
- Invoker:发起命令请求的人
- Command:封装命令
- Receiver:真正执行命令的人
为什么客户端不直接调用Receiver,而需要Inovker呢?这里Invoker有两个作用:
- 将客户端和Receiver解耦
- 能够附加一些能力,例如打日志,执行命令前的前置校验等
示例
执行命令的人,厨师
public class Cook {
// 煮饭
public void cookRice(){
}
// 炒菜
public void stirFry(){
}
}
命令
public interface Command {
void execute();
}
// 煮饭命令
public class CookRiceCommand implements Command {
private Cook cook;
public CookRiceCommand(Cook cook){
this.cook = cook;
}
@overrite
void execute(){
this.cook.cookRice();
}
}
// 炒菜命令
public class StirFryCommand implements Command {
private Cook cook;
public CookRiceCommand(Cook cook){
this.cook = cook;
}
@overrite
void execute(){
this.cook.stirFry();
}
}
发起命令的人,客人
public class Customer {
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void call(){
command.execute();
}
}
使用:
Customer customer = new Customer();
customer.setCommand(new CookRiceCommand());
customer.call();
customer.setCommand(new StirFryCommand());
customer.call();